import router from '@/router'
import setting from './setting'
//进度条及样式
//@ts-expect-error
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
nprogress.configure({ showSpinner: false })

//获取用户相关的小仓库内部token数据
import pinia from './stores'
import useUserStore from './stores/modules/user'
const store = useUserStore(pinia)

// 判断某个路由是否在 menuRoutes 中存在
const findRoute = (routes, name) => {
  for (const route of routes) {
    if (route.name === name) {
      return true
    }
    if (route.children && route.children.length > 0) {
      if (findRoute(route.children, name)) {
        return true
      }
    }
  }
  return false
}

// 设置全局前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
  //页面标题、进度条、token、username
  document.title = `${setting.title} - ${to.meta.title}`
  nprogress.start()
  const token = store.token
  const routt = store.menuRoutes
  const has_route = findRoute(routt, to.name) ? 1 : 0

  if (token) {
    // 已登录，判断角色权限
    console.log(token)
    if (has_route) {
      next()
    } else next('/403')
  } else {
    if (has_route) {
      if (!to.meta.requiresAuth) next()
    } else {
      return next('/403')
    }
  }
})

// 设置全局后置守卫（如果需要做统计等操作）
router.afterEach((to, from) => {
  // 你可以在这里做一些离开页面后的操作，比如页面统计等
  console.log(`Navigated to ${to.path}`)
})
